/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.dashboard;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.contacts.ContactBrowserActivity;
import com.phonebooksharing.android.async.DownloadNetworkImageTask;
import com.phonebooksharing.android.async.DownloadNetworkPostcardImageTask;
import com.phonebooksharing.android.async.DownloadNetworkVideoTask;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.widgets.drawable.FastBitmapDrawable;
import com.phonebooksharing.android.widgets.listview.ContactNearbyListView;
import com.phonebooksharing.android.widgets.listview.MessageListView;
import com.phonebooksharing.android.widgets.listview.PhotoListView;
import com.phonebooksharing.android.widgets.listview.PostcardListView;
import com.phonebooksharing.android.widgets.listview.VideoListView;
import com.phonebooksharing.android.widgets.pagination.ProgessbarListener;
import com.phonebooksharing.android.widgets.scroll.HorizontalScroller;
import com.phonebooksharing.dto.dashboard.DashboardReaderItem;
import com.phonebooksharing.dto.friend.ContactItem;
import com.phonebooksharing.dto.gallery.ImageGalleryItem;
import com.phonebooksharing.dto.gallery.PostCardItem;
import com.phonebooksharing.dto.gallery.VideoGalleryItem;

import dalvik.system.VMRuntime;

@SuppressWarnings("unchecked")
public class DashboardReader extends Activity implements View.OnLongClickListener, ProgessbarListener {
    
    public static final String QTY_FRIENDS_NEARBY = "0";
    public static final String QTY_PLACES_NEARBY = "1";
    public static final String QTY_MESSAGES = "2";
    public static final String QTY_POSTCARDS = "3";
    public static final String QTY_PHOTOS = "4";
    public static final String QTY_VIDEOS = "5";
    public static final String QTY_JOURNAL = "6";
    
    public static final String INITIAL = "i";
    
    private static final long INITIAL_HEAP_SIZE = 4*1024*1024;
    private ProgressBar progress;
    private long oldHeapSize;
    private HorizontalScroller hs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dash_reader);
        
        // Eliminate extra GCs during startup by setting the initial heap size to 4MB.
        oldHeapSize = VMRuntime.getRuntime().setMinimumHeapSize(INITIAL_HEAP_SIZE);
        
        progress = (ProgressBar)findViewById(android.R.id.progress);
        
        hs = (HorizontalScroller) findViewById(R.id.scroller);
        hs.setOnLongClickListener(this);
        loadReader();
    }
    
    protected void loadReader() {
        final Bundle b = getIntent().getExtras();
        final LayoutInflater li = LayoutInflater.from(this);
        
        int qtyFriendsNearby = b.getInt(QTY_FRIENDS_NEARBY);
        int qtyMessages = b.getInt(QTY_MESSAGES);
        int qtyPostcards = b.getInt(QTY_POSTCARDS);
        int qtyPlacesNearby = b.getInt(QTY_PLACES_NEARBY);
        int qtyPhotos= b.getInt(QTY_PHOTOS);
        int qtyVideos = b.getInt(QTY_VIDEOS);
        
        //begin nearby
        if(qtyFriendsNearby > 0) {
            View v = li.inflate(R.layout.dash_reader_layout, null);
            
            ContactNearbyListView clv = new ContactNearbyListView(this, qtyFriendsNearby, (TextView)v.findViewById(android.R.id.text2));
            
            ((ViewGroup)v.findViewById(android.R.id.list)).addView(clv);
            ((ImageView)v.findViewById(android.R.id.icon)).setImageResource(R.drawable.dash_friends_nearby);
            ((TextView)v.findViewById(android.R.id.text1)).setText("Contacts Nearby");
            
            clv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> av, View v, int loc, long id) {
                    final DashboardReaderItem<ContactItem> d = (DashboardReaderItem<ContactItem>) av.getAdapter().getItem(loc);
                    Intent i = new Intent(DashboardReader.this, ContactBrowserActivity.class);
                    i.putExtra(ContactBrowserActivity.FRIEND_ITEM, d.getItem());
                    startActivity(i);
                }
            });
            
            hs.addView(v);
        }
        
        if(qtyPlacesNearby > 0) {
            View v = li.inflate(R.layout.dash_reader_layout, null);
            ((ViewGroup)v.findViewById(android.R.id.list)).addView(new ContactNearbyListView(this, qtyPlacesNearby, (TextView)v.findViewById(android.R.id.text2)));
            ((ImageView)v.findViewById(android.R.id.icon)).setImageResource(R.drawable.dash_places_nearby);
            ((TextView)v.findViewById(android.R.id.text1)).setText("Places Nearby");
            hs.addView(v);
        }
        //end nearby
        
        if(qtyMessages > 0) {
            View v = li.inflate(R.layout.dash_reader_layout, null);
            ((ViewGroup)v.findViewById(android.R.id.list)).addView(new MessageListView(this, qtyMessages, (TextView)v.findViewById(android.R.id.text2)));
            ((ImageView)v.findViewById(android.R.id.icon)).setImageResource(R.drawable.dash_messages);
            ((TextView)v.findViewById(android.R.id.text1)).setText("Messages");
            hs.addView(v);
        }
        
        if(qtyPostcards > 0) {
            View v = li.inflate(R.layout.dash_reader_layout, null);
            PostcardListView pcl = new PostcardListView(this, qtyPostcards, (TextView)v.findViewById(android.R.id.text2));
            ((ViewGroup)v.findViewById(android.R.id.list)).addView(pcl);
            ((ImageView)v.findViewById(android.R.id.icon)).setImageResource(R.drawable.dash_post_card);
            ((TextView)v.findViewById(android.R.id.text1)).setText("Postcards");
            
            pcl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> av, View v, int loc, long id) {
                    final DashboardReaderItem<ContactItem> d = (DashboardReaderItem<ContactItem>) av.getAdapter().getItem(loc);
                    final PostCardItem f = (PostCardItem) d.getItem();

                    final int screenW = 480;
                    final int screenH = 320;

                    new DownloadNetworkPostcardImageTask(DashboardReader.this, d).execute(f.postcardID, screenW, screenH, d);
                }
            });
            
            hs.addView(v);
        }
        
        if(qtyPhotos > 0) {
            View v = li.inflate(R.layout.dash_reader_layout, null);
            PhotoListView plv = new PhotoListView(this, qtyPhotos, (TextView)v.findViewById(android.R.id.text2));
            ((ViewGroup)v.findViewById(android.R.id.list)).addView(plv);
            ((ImageView)v.findViewById(android.R.id.icon)).setImageResource(R.drawable.dash_photos);
            ((TextView)v.findViewById(android.R.id.text1)).setText("Photos");
            
            plv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> av, View v, int loc, long id) {
                    final DashboardReaderItem<ContactItem> d = (DashboardReaderItem<ContactItem>) av.getAdapter().getItem(loc);
                    final ImageGalleryItem f = (ImageGalleryItem) d.getItem();
                    final int photoW = f.width;
                    final int photoH = f.height;
                    final long photoID = f.photoID;

//                    final Display d1 = getWindowManager().getDefaultDisplay();
//                    final int screenW = d1.getWidth();
//                    final int screenH = d1.getHeight();
                    //TODO: shouldnt be hard coded, but it changes the values when portrait mode
                    final int screenW = 480;
                    final int screenH = 320;

                    final String[] s = new String[] { 
                                            "Original Size (" + photoW + " x " + photoH + ")", 
                                            "Screen Size (" + screenW + " x " + screenH + ")" 
                                          };

                    new AlertDialog.Builder(DashboardReader.this)
                                    .setTitle("Would you like to download?")
                                    .setItems(s, 
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {// original
                                new DownloadNetworkImageTask(DashboardReader.this).execute(photoID, photoW, photoH, d);
                            } else {// screen
                                new DownloadNetworkImageTask(DashboardReader.this).execute(photoID, screenW, screenH, d);
                            }
                        }
                    }).create().show();
                }
            });
            
            hs.addView(v);
        }
        
        if(qtyVideos > 0) {
            View v = li.inflate(R.layout.dash_reader_layout, null);
            
            VideoListView vlv = new VideoListView(this, qtyVideos, (TextView)v.findViewById(android.R.id.text2));
            
            ((ViewGroup)v.findViewById(android.R.id.list)).addView(vlv);
            ((ImageView)v.findViewById(android.R.id.icon)).setImageResource(R.drawable.dash_videos);
            ((TextView)v.findViewById(android.R.id.text1)).setText("Videos");
            
            vlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> av, View v, int loc, long id) {
                    final DashboardReaderItem<ContactItem> d = (DashboardReaderItem<ContactItem>) av.getAdapter().getItem(loc);
                    final VideoGalleryItem f = (VideoGalleryItem) d.getItem();

                    Global.setTempBitmap(new FastBitmapDrawable(((BitmapDrawable)((ImageView)v.findViewById(R.id.icon)).getDrawable()).getBitmap()));
                    new DownloadNetworkVideoTask(DashboardReader.this).execute(f.videoID, d);
                }
            });
            
            hs.addView(v);
        }
        
        int initial = b.getInt(INITIAL);
        hs.setDefaultScreen(initial);
        hs.initListView(initial);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "Mark All as Read").setIcon(android.R.drawable.ic_menu_agenda);
//        menu.add(1, 1, 1, "Sync").setIcon(android.R.drawable.ic_menu_preferences);
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        //menu.findItem(0).setEnabled(((Dashboarder)switcher.getCurrentView()).canMarkAsRead());
//        menu.findItem(0).setVisible(((Dashboarder)switcher.getCurrentView()).canMarkAsRead());
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0: {//mark as read
//                View v = switcher.getCurrentView();
//                Dashboarder d = (Dashboarder)v;
//                d.markAllAsRead();
//                //TODO: marks the current downloaded dashboard as deleted
//                //how about if there is more?
//                //should call the loadtasks again?!?
//                
//                View empty = LayoutInflater.from(this).inflate(R.layout.empty, null);
//                ((TextView)empty.findViewById(android.R.id.text1)).setText("There are no items to display here anymore.");
//                ((TextView)empty.findViewById(android.R.id.text2)).setText(d.getHeader());
//                ((ImageView)empty.findViewById(android.R.id.icon)).setImageResource(d.getHeaderIcon());
                
//                int dis = switcher.getDisplayedChild();
//                switcher.addView(empty, dis);
//                switcher.setDisplayedChild(dis);
//                switcher.removeView(v);
//                task = new RefreshTask().execute(this);
                return true;
            }
        }
        return false;
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        setResult(RESULT_OK);
    }

    @Override
    public void setProgressStatus(int i) {
        progress.setVisibility(i);
    }
    
    @Override
    public boolean onLongClick(View v) {
        // User long pressed on an item
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        hs.removeAllViews();
        hs = null;
        progress = null;
        VMRuntime.getRuntime().setMinimumHeapSize(oldHeapSize);
    }
}
